package com.gdou.crrp.service;


import com.gdou.crrp.entity.*;
import com.gdou.crrp.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.print.Doc;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class EvaluateService {
    @Autowired
    private ReservationRepository reservationRepository;
    @Autowired
    private EvaluateRepository evaluateRepository;
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private HospitalRepository hospitalRepository;
    @Autowired
    private DoctorRepository doctorRepository;
    @Autowired
    private DepartmentRepository departmentRepository;



    //查询到预约表所有信息并排序，提取最大id的内容:这里的isEval=0,表示获取已预约，未评价的（状态为“已付款”表示已预约）
    public Reservation findMaxIdIsEval(String name) {
        Sort sort = Sort.by(Sort.Direction.DESC, "time");//排序
        Date time = new Date();
        String status= "已付款";
        List<Reservation> reservations = reservationRepository.findAllByUserNameAndIsEvaluateAndTimeLessThanAndStatus(name,0,time,status,sort);
        if (reservations.size()==0){
           Reservation reservation = new Reservation();
            reservation.setDoctorName("");
            reservation.setDepartmentName("");
            reservation.setTime(null);
            reservation.setId(-1);
            reservations.add(reservation);
            return reservations.get(0);
        }else{
            return reservations.get(0);
        }
    }


    //查询预约表中预约时间超过的预约表，且状态为未评价
    public Evaluate saveEvaluate(Evaluate evaluate,int id) throws ParseException {
//        查询到当前预约表的信息
        Reservation reservation = reservationRepository.findById(id);
        evaluate.setContent(evaluate.getContent());
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //创建要显示的日期格式
        String  date = fmt.format(new Date());
        Date date1 = fmt.parse(date);
        evaluate.setEvaluateTime(date1);
        Evaluate evaluate1=  evaluateRepository.save(evaluate);
        reservation.setIsEvaluate(1);
        reservationRepository.save(reservation);
        return evaluate1;
    }
//    public List<Evaluate> findAllEvaluate(){
//    }



    //通过写入session的用户id查找到我的姓名
    public String findMyName(int id){
        User user = userRepository.findById(id);
        String name  = user.getName();
        return  name;
    }

    //通过用户id查找昵称
//    public String findMyNickName(int id){
//
//        return
//    }

    //获取所有我评价过的id,并以分页形式显示
    public Page<Evaluate> showMyEvalIsEval(int uid , Pageable pageable){
        return evaluateRepository.findAllByUid(uid,pageable);
    }

    public List<Reservation> showMyEvalNoEval(String name,int isEvaluate,int page,int size) {
                    Date date = new Date();
        return reservationRepository.findAllByUserNameAndIsEvaluateAndTimeLessThan(name,isEvaluate,date, PageRequest.of(page,size, Sort.Direction.DESC,"time")).getContent();
    }

    public int countId(String name,int isEvaluate){
        Date date = new Date();
        return  reservationRepository.countIdByUserNameAndAndIsEvaluateAndTimeLessThan(name,isEvaluate,date);

    }

    public Evaluate saveSecondEval(int id,String content){
        Evaluate evaluate = evaluateRepository.findById(id);
        evaluate.setAddContent(content);
        evaluate.seteTwiceTime(new Date());
        evaluate.setIsEvalTwice(1);
        return  evaluateRepository.save(evaluate);
    }

    //删除选中的评论
    public void deleteEval(int id){
        evaluateRepository.deleteEvaluateById(id);
    }

    public List<Hospital> findAllHospital(){
        return hospitalRepository.findAll();
    }

//找到所有的医生，对应搜索框的内容
    public List<String> findAllDoctor(){
        return doctorRepository.find();
    }

    public Doctor findDoctorByName(String dn){
        return doctorRepository.findByName(dn).get(0);
    }

    /**
     * 处理三个条件的查询
     * @param hname
     * @param dname
     * @param rname
     * @return
     */
    public Doctor findByHospitalName(String hname,String dname,String rname){
        Hospital hospital = hospitalRepository.findByName(hname);
        Department department = departmentRepository.findByNameAndHid(dname, hospital.getId());
        Doctor doctor = doctorRepository.findByDidAndName(department.getDid(), rname);
        return  doctor;
    }

    public  List<Doctor> findByDepartmentId(String hname,String dname){
        Hospital hospital = hospitalRepository.findByName(hname);
        Department department = departmentRepository.findByNameAndHid(dname, hospital.getId());
        List<Doctor> doctors = doctorRepository.findByDid(department.getDid());
        return doctors;
    }
    //按医生姓名直接查找
    public List<Doctor> findByDoctorName(String doctorName){
        List<Doctor> doctors = doctorRepository.findByName(doctorName);
        return doctors;
    }

    public List<Integer> findDoctorGood(String name){
        return  evaluateRepository.findLevel(name);
    }

    //保存医生
    public void saveDoctorRate(Doctor doctor){
       doctorRepository.save(doctor);
    }

    //计算好评率
    public String countRate(List<Integer> goods,int level){
        int count= 0;
        for (int i = 0; i < goods.size(); i++) {
            count =count+ goods.get(i);
        }
        System.out.println("count："+count);
        int size=goods.size();
            size=size+1;
        float rate =(float)((count+level)*100)/(size*5);
        System.out.println(((count+level)*100)/(size*5));
        DecimalFormat decimalFormat1 = new DecimalFormat("0.0");
        String goodrate = decimalFormat1.format(rate);
        return  goodrate;
    }



    public List<Evaluate> findEvalByDoctor(String name){
      return   evaluateRepository.findAllByDoctorName(name);
    }


//e.id,e.evaluateTime,e.content,e.isEvalTwice,e.level,e.eTwiceTime,e.addContent,a.name
    public List<Object> listAllEval(String name){
        List<Object> result = evaluateRepository.findList(name);
        System.out.println("service:"+result);
        List<Object> list = new ArrayList<>();
        for (Object row:result){
            String a=null;
            String b=null;
            Object[] rowArray = (Object[]) row;
            Map<String, Object> mapArr = new HashMap<>();
            mapArr.put("id", rowArray[0]);
            if (rowArray[1]!=null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                b= sdf.format(rowArray[1]);
            }
            mapArr.put("evaluateTime", b);
            mapArr.put("content", rowArray[2]);
            mapArr.put("isEvalTwice", rowArray[3]);
            mapArr.put("level", rowArray[4]);
            if (rowArray[5]!=null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                a= sdf.format(rowArray[5]);
            }
            mapArr.put("eTwiceTime", a);
            mapArr.put("addContent", rowArray[6]);
            mapArr.put("name", rowArray[7]);
            list.add(mapArr);
        }
        return list;
    }


    //-------------------------------------------------获取医生评论模块
//获取不同等级的好评个数
  public int countStars(String doctorName,int num){
      List<Evaluate> countStar = new ArrayList<>();
        if (num==3)
            countStar = evaluateRepository.findAllByDoctorNameAndLevelBetween(doctorName,2,4);
        else
            countStar= evaluateRepository.findAllByDoctorNameAndLevel(doctorName,num);
       return  countStar.size();
  }
//获取追加的用户的个数
  public int countaddContentNum(String doctorName){
        List<Evaluate> countNum=evaluateRepository.findAllByDoctorNameAndAddContentIsNotNull(doctorName);
        return countNum.size();
    }
    //获取不同等级的好评
    public List<Object> evalDiffLevel(String doctorName,int num) {
        List<Object> evalAS = new ArrayList<>();
        if (num==3){
          evalAS = evaluateRepository.findAllByDoctorThree(doctorName);
        }else {
            evalAS = evaluateRepository.findAllByDoctorFiveOne(doctorName,num);
        }
        List<Object> list = new ArrayList<>();
        for (Object row1 : evalAS) {
            String a=null;
            String b=null;
            Object[] rowA = (Object[])row1;
            Map<String, Object> mapA = new HashMap<>();
            mapA.put("id", rowA[0]);
            if (rowA[1]!=null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                b= sdf.format(rowA[1]);
            }
            mapA.put("evaluateTime", b);
            mapA.put("content", rowA[2]);
            mapA.put("isEvalTwice", rowA[3]);
            mapA.put("level", rowA[4]);
            if (rowA[5]!=null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                a= sdf.format(rowA[5]);
            }
            mapA.put("eTwiceTime", a);
            mapA.put("addContent", rowA[6]);
            mapA.put("name", rowA[7]);
            list.add(mapA);
        }
        System.out.println("list:"+list);
        return list;
    }


    public List<Object> listAllEvalHasAdd(String name){
        List<Object> result = evaluateRepository.findEvalAddContentNoNull(name);
        System.out.println("service:"+result);
        List<Object> list = new ArrayList<>();
        for (Object row:result){
            String a=null;
            String b=null;
            Object[] rowArray = (Object[]) row;
            Map<String, Object> mapArr = new HashMap<>();
            mapArr.put("id", rowArray[0]);
            if (rowArray[1]!=null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                b= sdf.format(rowArray[1]);
            }
            mapArr.put("evaluateTime", b);
            mapArr.put("content", rowArray[2]);
            mapArr.put("isEvalTwice", rowArray[3]);
            mapArr.put("level", rowArray[4]);
            if (rowArray[5]!=null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                a= sdf.format(rowArray[5]);
            }
            mapArr.put("eTwiceTime", a);
            mapArr.put("addContent", rowArray[6]);
            mapArr.put("name", rowArray[7]);
            list.add(mapArr);
        }
        return list;
    }

    //获取追加过的评论
    public List<Evaluate> evalAboutAddContent(String doctorName){
        List<Evaluate> aaa=evaluateRepository.findAllByDoctorNameAndAddContentIsNotNull(doctorName);
        return aaa;
    }




//    public List<Object> voteListTest(ArticleVoteRepository voteRepository, Integer userId) {
//        this.voteRepository = voteRepository;
//        List<Object> result = voteRepository.findVoteList(userId);
//        for (Object row : result) {
//            Object[] rowArray = (Object[]) row;
//            Map<String, Object> mapArr = new HashMap<String, Object>();
//            mapArr.put("id", rowArray[0]);
//            mapArr.put("title", rowArray[1]);
//            mapArr.put("count", rowArray[2]);
//            mapArr.put("flag", rowArray[3]);
//            list.add(mapArr);
//        }
//        return list;
//
//    }
}
